<?php

namespace App\Http\Controllers\Api\V6;

use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use DB, Validator;
use Illuminate\Http\Request;
use App\Modules\EntMemberInfo;
use App\Modules\EntMemberDRP;

use App\Common\MobileMassege;
use App\Common\ApiData;
use App\Models\V6\MemberModel;
use App\Models\V6\MessageModel;
use App\Models\V6\DrpModel;
use App\Common\Jpush;
use App\Common\ApiToken;


class MemberController extends BaseController
{

    protected $fileTypes = ['jpg', 'jpeg', 'png'];

    /**
     * 保存用户提交的建议
     * */
    public function suggestionsStore(Request $request)
    {
        $userId     = $request->input('userId');
        $content    = $request->input('content');
        $memberModel= new MemberModel();
        $userInfo   = $memberModel->get_member_info_by_id($userId);

        $data       = [
            'Contents'  => $content,
            'ContactUs' => $userInfo->YourName ?? $userInfo->UserID,
        ];

        $memberModel->add_suggestion($data);

        $mobileMessage  = new MobileMassege();
        $mobileMessage->mobile = system_log('kefu_mobile');
        $mobileMessage->send_msg("用户{$userInfo->UserName}{$userInfo->NickName}反馈了一个意见,内容为：".$content);

        return apiData()->send();
    }


    /**
     * 读取会员详细
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_member_info(Request $request)
    {
        $userId         = $request->input('userId');
        $memberModel    = new MemberModel();
        $memberInfo     = $memberModel->get_member_info_by_id($userId);

        if (!$memberInfo) {

            return response()->json(['message' => "用户不存在", 'code' => 2039]);
        }

        //$msgModel                 = new MessageModel();
        //$unReadMsgNumber          = $msgModel->get_unreaded_message_number($userId);
        //$memberInfo->unReadMsgNum = $unReadMsgNumber;

        return apiData()->set_data('userInfo',$memberInfo)->send(200,"ok");
    }


    /**
     * 登录入口
     * 对新用户返回微信的数据
     * */
    public function login(Request $request)
    {
        //微信端获取的code
        $code           = $request->input('code');

        //根据code来获取微信的openId
        $miniConfig     = config("wx.mini");

        $params         = [ "appid"     => $miniConfig["appId"],
                            "secret"    => $miniConfig["appSecret"],
                            "js_code"   => $code,
                            "grant_type"=> "authorization_code",
                        ];

        $params         = http_build_query($params);
        $url            = "https://api.weixin.qq.com/sns/jscode2session?".$params;
        $result         = file_get_contents($url);

        $wxInfo         = json_decode($result);

        if(!isset($wxInfo->unionid) && false){

            return apiData()->send(2002,"获取微信信息错误");
        }

        $unionId    = isset($wxInfo->unionid) ? $wxInfo->unionid : "";
        $openId     = $wxInfo->openid;
        $sessionKey = $wxInfo->session_key;
        if(!($unionId||$openId))
        {

        	mylogger("无法获取到微信正常信息:".$result);
        	return apiData()->send(2002,"获取微信信息错误");
        }

        $userModel = new MemberModel();

        //检查用户是否存在
        $userInfo   = $userModel->get_miniapp_member_info($openId);

        if(!$userInfo && $unionId){

            $userInfo   = $userModel->get_member_info_by_unionid($unionId);
        }

        if(!$userInfo){

            return apiData()
                ->set_data("unionId",$unionId)
                ->set_data('openId',$openId)
                ->send(2003,"用户不存在");
        }
        mylogger("=======================");
        mylogger("ipenid=".$openId.";unionid=".$unionId);

        //登录成功，更新loginKey
        $loginKey   = md5(create_member_number());
        $userModel->update_member_info([
            "UserID"        => $userInfo->UserID,
            'LoginKey'      => $loginKey,
            'mini_openid'   => $openId
        ]);
        $userInfo->LoginKey = $loginKey;
        return apiData()->set_data("userInfo",$userInfo)->send();
    }


    /**
     * 验证手机号是否已经注册
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkMobile(Request $request)
    {
        //return response()->json(['message' => 'ok', 'code' => 200]);
        $result = 'no';
        $mobile = $request->input('mobile');
        if (empty($mobile)) {
            return response()->json(['message' => $result, 'code' => 3003]);
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile($mobile);
        if ($memberInfo) {
            return response()->json(['message' => $result, 'code' => 3002]);
        } else {
            return response()->json(['message' => 'ok', 'code' => 200]);
        }
    }


    /**
     * 发送短信
     * */
    public function add_mobile_code(Request $request)
    {

        $usermobile  = $request->input('mobile');
        $countryCode = $request->input('countryCode');


        if (empty($usermobile)) {
            return response()->json(['message' => "缺少手机号码", 'code' => 3003]);
        }


        $mobileMessage              = new MobileMassege();
        $mobileMessage->mobile      = $usermobile;
        $mobileMessage->countryCode = $countryCode;
        $res                        = $mobileMessage->check_can_send_code($usermobile);
        if ($res == false) {
            return response()->json(['message' => $mobileMessage->error, 'code' => 3008]);
        }

        $res = $mobileMessage->send_valid_code();
        if ($res == false) {
            return response()->json(['message' => $mobileMessage->error, 'code' => 3009]);
        } else {
            return response()->json(['message' => 'ok', 'code' => 200]);
        }
    }


    /**
     * 验证手机验证码
     * @param Request $request
     * @return string
     */
    public function check_mobile_code(Request $request)
    {
        $result       = 'no';
        $rules        = [
            'securitycode' => 'required',
            'mobile'       => 'required'
        ];
        $messages     = [
            'securitycode.required' => 2006,
            'mobile.required'       => 2002
        ];
        $securitycode = $request->input('securitycode');
        $mobile       = $request->input('mobile');
        $params       = ['mobile' => $mobile, 'securitycode' => $securitycode];
        $v            = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['status' => false, 'code' => $v->messages()->first()]);
        }
        $mobileMessage = new MobileMassege();
        $res           = $mobileMessage->check_valid_code($mobile, $securitycode);
        if ($res) {
            return response()->json(['message' => 'ok', 'code' => 200]);
        } else {
            return response()->json(['message' => $result, 'code' => 3001]);
        }
    }


    /**
     * 手机注册
     *
     * */
    public function register(Request $request)
    {

        $mobile     = $request->input('mobile');
        $mobileCode = $request->input('mobileCode');
        $unionId    = $request->input('unionId');
        $openId     = $request->input('openId');
        $nickName   = $request->input('nickName');
        $version    = $request->input('version');

        $rules = [
            'mobile'     => [$mobile, "手机号为空", 2001],
            'yourname'   => [$nickName, "用户名为空", 2002],
            'mobilecode' => [$mobileCode, "验证码为空", 2003],
            "openId"     => [$openId,"缺少unionid",2004]
        ];

        $result = $this->check_params($rules);
        if ($result->status == false) {

            return apiData()->send($result->code,$result->message);
        }

        //1.验证校验码是否正确
        $messageModel = new MobileMassege();
        $result       = $messageModel->check_valid_code($mobile, $mobileCode);


        if ($result !== true) {

            return apiData()->send(3001,"验证码错误");
        }

        $memberModel = new MemberModel();

        //3.检查这个手机号是否存在,如果存在则绑定
        $userInfo   = $memberModel->get_member_info_by_mobile($mobile);

        $wxInfo  = $memberModel->get_miniapp_member_info($openId);
        if(!$wxInfo && $unionId){
            $wxInfo = $memberModel->get_member_info_by_unionid($unionId);
        }

        if($userInfo&&$wxInfo)
        {
            return apiData()->send(3002,"手机号已被占用");
        }

        if(!$userInfo && $wxInfo) //有微信账号，还没有绑定手机号
        {
            $userInfo = $wxInfo;
        }

        $nickName   = emoji_text_encode($nickName);
        $loginKey   = md5(create_member_number());
        $nextVersion    = env('MINI_APP_NEXT_VERSION');

        if($version == $nextVersion){ //审核特用,自动成功会员

            $status     = 1;
            $endTime    = (date('Y')+1)."-".date('m')."-".date('d');

        }elseif($userInfo){ //历史用户，保留不变

            $status     = $userInfo->States;
            $endTime    = $userInfo->MemEndTime;

        }else{ //新用户，无特权

            $status     = 0;
            $endTime    = "";
        }

        if($userInfo){ //用户存在，绑定相关账户

            $newMemberInfo  = [
                "States"        => $status,
                "UserID"        => $userInfo->UserID,
                "wx_unionid"    => $unionId,
                "mini_openid"   => $openId,
                "UserName"      => $mobile,
                "head_img"      => $userInfo->head_img ? $userInfo->head_img : $request->input('headImg'),
                "NickName"      => $nickName,
                "LoginKey"       => $loginKey,
                "MemEndTime"    => $endTime
            ];
            $memberModel->update_member_info($newMemberInfo);
            $userId     = $userInfo->UserID;

        }else{

            //不存在用户，则新增

            $data = [
                "States"       => $status,
                "MemNumber"    => create_member_number(),
                "MemEndTime"   => $endTime,
                "UserName"     => $mobile,
                "NickName"     => $nickName,
                "YourName"     => $nickName,
                "RegisterType" => "mini",
                "wx_unionid"   => $unionId,
                "mini_openid"  =>$openId,
                'head_img'     => $request->input('headImg',''),
                'FilePath1'    => $request->input('headImg',''),
                'DeleteMark'   => 1,
                'LoginKey'     => $loginKey
            ];
            $userId     = $memberModel->register($data);
        }

        $userInfo       = $memberModel->get_member_info_by_id($userId);

        $messageModel->delete_code($mobile, $mobileCode);

        return apiData()->set_data("userInfo",$userInfo)->send(200,'success');
    }

    /*
     * 更新用户信息
     * */
    public function update_member_info(Request $request)
    {

        $userId  = $request->input('userId');
        $appKey  = $request->input('key');
        $apiData = new ApiData();

        $params = [
            'userId' => [$userId, '缺少用户ID', 2001],
            'appKey' => [$appKey, '缺少设备ID', 2002]
        ];

        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->message = $checkResult->message;
            $apiData->code    = $checkResult->code;
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_id($userId);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = 3056;

            return $apiData->send();
        }

        $colum    = ['UserName', 'YourName', 'NickName', 'app_openid', 'company_id', 'mobileCode'];
        $data     = ['UserID' => $userId];
        $userInfo = $request->input('userInfo');
        if ($userInfo) {

            $clientType = $request->header('Client-type', '');
            if ($clientType) {
                $userInfo = json_decode(urldecode($userInfo));
            } else {
                (String)$userInfo = $userInfo;
                $userInfo = json_decode($userInfo);
            }

            foreach ($userInfo as $key => $v) {
                if (in_array($key, $colum)) {
                    $data[$key] = $v;
                }
            }
        }

        if (isset($data['UserName'])) { //如果包含有手机号码,则需要验证

            if ((!isset($data['mobileCode'])) || empty($data['mobileCode'])) {
                $apiData->message = "修改手机号需要验证码";
                $apiData->code    = 3057;

                return $apiData->send();
            }

            $mobileModel = new MobileMassege();
            $result      = $mobileModel->check_valid_code($data['UserName'], $data['mobileCode']);

            if ($result !== true && false) {
                $apiData->message = $result;
                $apiData->code    = 3058;

                return $apiData->send();
            }


            $oldUserInfo = $memberModel->get_member_info_by_mobile($data['UserName']);
            //检查手机号是否被绑定 1.当前手机号为空 2.手机号码被使用
            if (empty($memberInfo->UserName) && $oldUserInfo != false && $oldUserInfo->AppKey != $appKey && $oldUserInfo->AppKey != '') {
                $apiData->message = "手机号已经被绑定";
                $apiData->code    = 3059;

                return $apiData->send();
            }
            unset($data['mobileCode']);


            if ($oldUserInfo != false) {
                if ($oldUserInfo->UserID != $memberInfo->UserID) {

                    //绑定手机号
                    //1.取出新的用户信息


                    //2.修改以前的信息
                    $data['wx_unionid'] = $memberInfo->wx_unionid;
                    $data['app_openid'] = $memberInfo->app_openid;
                    $data['head_img']   = $memberInfo->head_img;
                    $data['UserID']     = $oldUserInfo->UserID;
                    $data['AppKey']     = $appKey;

                    $data['MemEndTime'] = strtotime($oldUserInfo->MemEndTime) > strtotime($memberInfo->MemEndTime) ? $oldUserInfo->MemEndTime : $memberInfo->MemEndTime;
                    $data['personal_end_time'] = strtotime($oldUserInfo->personal_end_time) > strtotime($memberInfo->personal_end_time) ? $oldUserInfo->personal_end_time:$memberInfo->personal_end_time;

                    //3.销毁新的信息
                    $oldData               = [];
                    $oldData['UserID']     = $userId;
                    $oldData['DeleteMark'] = 0;
                    $memberModel->update_member_info($oldData);
                    $apiToken   = new ApiToken();
                    $apiToken->create_only_token($oldUserInfo->UserID);
                }
            }
        }

        $memberModel->update_member_info($data);
        $apiData->message = "修改成功";
        $apiData->code    = 200;

        return $apiData->send();
    }



    /*=========================================
    **************** 用户中心 *****************
    ==========================================*/


    /**
     * 收藏记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_collected(Request $request)
    {

        $userId         = $request->input('tokenUserId');
        $memberModel    = new MemberModel();
        $memberInfo     = $memberModel->get_member_info_by_id($userId);
        //1.获取收藏的视频
        $collectBooks = DB::table('bookcollect as a')
            ->leftJoin('bookinfo as b','a.BookID','=','B.BookID')
            ->select('a.ColID as colId','b.BookID','a.AddDate','b.book_img','b.BookTitle')
            ->where('a.MemNumber',$memberInfo->MemNumber)
            ->get();

        foreach ($collectBooks as $collect)
        {
            $collect->book_img = env('HOST').$collect->book_img;
        }

        //2.获取收藏的音频
        $collectAudios = DB::table('audio_collect as a')
            ->leftJoin('audioday as b','a.audio_id','=','b.AudioID')
            ->select('b.AudioID','a.id as colId','b.AudioTitle','b.FilePath1 as audioUrl','a.created_at as AddDate')
            ->where('user_id',$userId)
            ->get();


        return apiData()
            ->set_data('collectedBooks',$collectBooks)
            ->set_data('collectedAudio',$collectAudios)
            ->send(200,'ok');
    }


    /**
     * 删除收藏
     * */
    public function delete_collected(Request $request)
    {
        $type   = $request->input('type');
        $colIds = $request->input('colIds');
        $colIds = json_decode($colIds,true);
        if(! is_array($colIds))
        {
            return apiData()->send(4001,'id集合错误');
        }

        switch($type)
        {
            case 'book':
                $table  = "bookcollect";
                $key    = "ColID";
                break;
            case 'audio':
                $table  = "audio_collect";
                $key    = "id";
                break;
            default:
                return apiData()->send(4002,'类型错误');
                break;
        }
        DB::table($table)->whereIn($key,$colIds)->delete();
        return apiData()->send(200,'ok');
    }

}









